/*
 * Copyright (c) 2022 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "core/components_ng/pattern/custom/custom_node_pattern.h"

#include "base/utils/utils.h"
#include "core/components_ng/pattern/custom/custom_measure_layout_node.h"

namespace OHOS::Ace::NG {

bool CustomNodePattern::OnDirtyLayoutWrapperSwap(
    const RefPtr<LayoutWrapper>& dirty, const DirtySwapConfig& config)
{
    if (config.skipMeasure && config.skipLayout) {
        return false;
    }
    CHECK_NULL_RETURN(dirty, false);
    renderFunction_ = nullptr;
    auto host = AceType::DynamicCast<CustomMeasureLayoutNode>(GetHost());
    CHECK_NULL_RETURN(host, false);
    auto children = host->GetMeasureLayoutParam();
    if (children) {
        UpdateActiveChildren(children->GetLayoutedList());
    }
    return false;
}

void CustomNodePattern::UpdateActiveChildren(const std::set<int32_t>& activeChildren)
{
    auto host = GetHost();
    CHECK_NULL_VOID(host);
    for (auto index : activeChildren_) {
        if (activeChildren.find(index) == activeChildren.end()) {
            host->RemoveChildInRenderTree(index);
        }
    }
    activeChildren_ = activeChildren;
}
} // namespace OHOS::Ace::NG
